<template>
  <a-card :bordered="false">
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="4">
        <a-form-item field="title" label="標題">
          <a-input v-model="searchForm.title" placeholder="請輸入標題" allow-clear />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-button v-auth="[1, 2]" type="primary" style="margin: 0 2px" @click="init(1)">搜索</a-button>
        <a-button v-auth="[1, 2]" style="margin: 0 2px" @click="clearSearch">清空</a-button>
        <a-button v-auth="[1, 2]" type="primary" style="margin: 0 2px" @click="openAddPopup">添加</a-button>
      </a-col>
    </a-row>

    <div ref="crudContentRef">
      <a-table
        :loading="loading"
        :scroll="{ x: '100%', y: '100%' }"
        :columns="columns"
        :pagination="false"
        :data="data">
        <template #sendTime="{ record }">
          {{ +new Date(record.sendTime) < +new Date() ? '已發送' : '未發送' }} <br />
        </template>
        <template #ctime="{ record }">
          發送時間：{{ dateFormat(record.sendTime) }} <br />
          實際時間：{{ dateFormat(record.actualSendTime) }} <br />
          創建時間：{{ dateFormat(record.ctime) }} <br />
          修改時間：{{ dateFormat(record.mtime) }}
        </template>
        <template #optional="{ record }">
          <a-link v-auth="[1, 2]" v-if="false" @click="openEditPopup(record)"> 查看 </a-link>
          <a-link v-auth="[1, 2]" v-if="false" status="success" @click="sendNotifications(record)"> 立即發送 </a-link>
          <a-popconfirm content="確定刪除嗎？" @before-ok="deleteNotifications(record)" type="warning">
            <a-link v-auth="[1, 2]" status="danger"> 刪除 </a-link>
          </a-popconfirm>
        </template>
      </a-table>
    </div>
    <div class="mt-2 text-right" v-if="data.length > 0">
      <a-pagination
        :total="pageObj.total"
        show-total
        show-page-size
        :page-size-options="[10, 20, 30, 50, 100]"
        @page-size-change="pageSizeChangeHandler"
        @change="pageChangeHandler"
        v-model:current="pageObj.page"
        :page-size="pageObj.pageSize"
        style="display: inline-flex" />
    </div>
    <a-modal
      v-model:visible="visible"
      title="添加"
      width="80%"
      :ok-loading="btnLoading"
      @cancel="close"
      @before-ok="submit">
      <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
        <a-form-item label="標題" field="title">
          <a-input v-model="formData.title" placeholder="請輸入標題" />
        </a-form-item>
        <a-form-item label="內容" field="content">
          <a-spin :loading="editorUploadLoading">
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode" />
              <Editor
                style="height: 300px; overflow-y: hidden"
                v-model="formData.content"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated" />
            </div>
          </a-spin>

          <!-- <a-input v-model="formData.content" placeholder="請輸入內容" /> -->
        </a-form-item>
        <a-form-item label="類型" v-if="false" field="type">
          <a-radio-group v-model="formData.type" type="button">
            <a-radio :value="1">系統通知</a-radio>
            <a-radio :value="2">活動通知</a-radio>
            <a-radio :value="3">獎勵通知</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="目標人羣" field="targetType">
          <a-radio-group v-model="formData.targetType" type="button">
            <a-radio :value="1">所有用戶</a-radio>
            <a-radio :value="2">指定用戶分組</a-radio>
            <a-radio :value="3">指定用戶</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="指定用戶分組" v-if="formData.targetType == 2" field="groupIds">
          <a-select
            placeholder="請選擇用戶分組"
            multiple
            v-model="formData.groupIds"
            :max-tag-count="5"
            allow-clear
            @dropdown-reach-bottom="handleReachBottom">
            <a-option v-for="item in selectGroupUserList" :key="item.id" :value="item.id"
              >{{ item.name }}({{ item.user_count }})</a-option
            >
          </a-select>
        </a-form-item>
        <a-form-item label="指定用戶" v-if="formData.targetType == 3" field="userIds">
          <a-select
            placeholder="請選擇用戶"
            multiple
            v-model="formData.userIds"
            :max-tag-count="5"
            allow-clear
            @dropdown-reach-bottom="handleReachBottom">
            <a-option v-for="item in selectUserList" :key="item.uid" :value="item.uid"
              >{{ item.game_nickname }}({{ item.uid }})({{ item.title }})</a-option
            >
          </a-select>
        </a-form-item>
        <a-form-item label="默認發送時間" field="sendTime">
          <a-date-picker
            show-time
            placeholder="請選擇發送時間，不選擇則立即發送"
            v-model="sendTime"
            :time-picker-props="{
              defaultValue: '00:00:00',
            }"
            class="w-full"
            format="YYYY-MM-DD HH:mm:ss"
            @change="onChange" />
        </a-form-item>
        <a-form-item label="遊戲模版id" field="templateId">
          <a-input v-model="formData.templateId" placeholder="請輸入遊戲模版id" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick, onBeforeUnmount, shallowRef } from 'vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Message } from '@arco-design/web-vue'
import notificationsApi from '@/api/notifications'
import userGroupApi from '@/api/userGroup'
import tool from '@/utils/tool'
const mode = 'simple'
const editorRef = shallowRef()
const editorUploadLoading = ref(false)
const toolbarConfig = {
  excludeKeys: ['codeBlock', 'fullScreen', 'undo', 'redo'],
}
const editorConfig = { placeholder: '請輸入內容...', MENU_CONF: {} }
const token = tool.local.get(import.meta.env.VITE_APP_TOKEN_PREFIX)
editorConfig.MENU_CONF['uploadImage'] = {
  server: import.meta.env.VITE_APP_BASE_URL + 'api/v1/admin/image/upload',
  fieldName: 'file',
  maxFileSize: 1 * 1024 * 1024, // 1M
  maxNumberOfFiles: 1,
  headers: {
    Authorization: `Bearer ${token}`,
  },
  withCredentials: true,
  timeout: 6 * 10000, // 5 秒
  onBeforeUpload(file) {
    let fileKey = ''
    for (const key in file) {
      fileKey = key
    }
    if (file[fileKey].size / 1024 / 1024 > 1) {
      Message.error('圖片大小不能超過1MB')
      return false
    }
    editorUploadLoading.value = true
    return file
  },
  onFailed() {
    editorUploadLoading.value = false
    Message.error('圖片上傳失敗')
  },
  onError() {
    editorUploadLoading.value = false
    Message.error('圖片上傳失敗')
  },
  customInsert(res, insertFn) {
    const url = res.data
    editorUploadLoading.value = false
    insertFn(url, '', '')
  },
}
const sendTime = ref('')
const onChange = (dateString) => {
  if (dateString) {
    formData.value.sendTime = dateString
  } else {
    formData.value.sendTime = ''
  }
}
const handleReachBottom = () => {
  if (formData.value.targetType == 2) {
    if (selectUserGroupPageObj.page * selectUserGroupPageObj.pageSize > selectUserGroupPageObj.total) return
    init2(selectUserGroupPageObj.page + 1)
  }
  if (formData.value.targetType == 3) {
    if (selectUserPageObj.page * selectUserPageObj.pageSize > selectUserPageObj.total) return
    init3(selectUserPageObj.page + 1)
  }
}
// 組件銷毀時，也及時銷毀編輯器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 記錄 editor 實例，重要！
}

const pageObj = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
})
const searchForm = reactive({
  title: '',
})
const clearSearch = () => {
  searchForm.title = ''
}
const columns = ref([
  {
    title: '標題',
    dataIndex: 'title',
    ellipsis: true,
  },
  {
    title: '內容',
    dataIndex: 'content',
    ellipsis: true,
  },
  {
    title: '類型',
    dataIndex: 'typeDesc',
    width: 100,
  },
  // {
  //   title: '目標人羣',
  //   dataIndex: 'targetTypeDesc',
  //   slotName: 'targetTypeDesc',
  //   width: 100,
  // },
  {
    title: '網頁發送狀態',
    dataIndex: 'sendTime',
    slotName: 'sendTime',
    width: 80,
  },
  {
    title: '遊戲發送狀態',
    dataIndex: 'gameSendStatusDesc',
    slotName: 'gameSendStatusDesc',
    width: 80,
  },
  {
    title: '時間',
    dataIndex: 'ctime',
    slotName: 'ctime',
    width: 270,
  },
  {
    title: '操作',
    slotName: 'optional',
    width: 100,
  },
])
const rules = reactive({
  title: [{ required: true, message: '請輸入標題' }],
  content: [{ required: true, message: '請輸入內容' }],
})
const type = ref('add')
const visible = ref(false)
const btnLoading = ref(false)
const formRef = ref(null)

const formData = ref({
  title: '',
  content: '',
  type: 1,
  targetType: 1,
  groupIds: [],
  userIds: [],
  sendTime: '',
  templateId: '',
})
const openAddPopup = () => {
  type.value = 'add'
  sendTime.value = ''
  formData.value = {
    title: '',
    content: '',
    type: 1,
    targetType: 1,
    groupIds: [],
    userIds: [],
    sendTime: '',
    templateId: '',
  }
  visible.value = true
}
const openEditPopup = async (row) => {
  const res = await notificationsApi.getNotificationsDetail(row.id)
  return
  type.value = 'edit'
  sendTime.value = row.sendTime
  formData.value = {
    id: row.id,
    title: row.title,
    content: row.content,
    type: row.type,
    targetType: row.targetType || 1,
    groupIds: row.groupIds || [],
    userIds: row.userIds || [],
    sendTime: row.sendTime,
    templateId: row.templateId,
  }
  visible.value = true
}
const close = () => {
  visible.value = false
  btnLoading.value = false
}
const submit = async (done) => {
  const validate = await formRef.value?.validate()
  if (validate) return done(false)
  try {
    await notificationsApi.createNotifications(formData.value)
    close()
    Message.success(`添加成功！`)
    init()
  } catch (error) {
    btnLoading.value = false
    done(false)
  }
}
const sendNotifications = async (row) => {
  loading.value = true
  try {
    await notificationsApi.sendNotifications(row.id)
    loading.value = false
    Message.success(`發送成功！`)
    init(pageObj.page)
  } catch (error) {
    loading.value = false
  }
}
const deleteNotifications = async (row) => {
  try {
    await notificationsApi.deleteNotifications(row.id)
    Message.success(`刪除成功！`)
    init(pageObj.page)
  } catch (error) {
    return false
  }
}
const data = ref([])

const pageSizeChangeHandler = async (pageSize) => {
  pageObj.page = 1
  pageObj.pageSize = pageSize
  init()
}
const pageChangeHandler = async (currentPage) => {
  pageObj.page = currentPage
  init(currentPage)
}

const loading = ref(false)
const init = async (pageNum = 1) => {
  loading.value = true
  try {
    const res = await notificationsApi.getNotificationsList({
      pageNum,
      pageSize: pageObj.pageSize,
      title: searchForm.title,
    })
    loading.value = false
    pageObj.total = res.data.total
    pageObj.page = res.data.pageNum
    pageObj.pageSize = res.data.pageSize
    data.value = res.data.list
  } catch (error) {
    loading.value = false
  }
}
init()
const selectUserGroupLoading = ref(false)
const selectUserGroupPageObj = reactive({
  page: 1,
  total: 0,
  pageSize: 10,
})
const selectGroupUserList = ref([])
const init2 = async (page = 1) => {
  if (selectUserGroupLoading.value) return
  selectUserGroupLoading.value = true
  try {
    const res = await userGroupApi.getUserGroupList({
      page,
      page_size: selectUserGroupPageObj.pageSize,
    })
    selectUserGroupPageObj.total = res.data.total
    selectUserGroupPageObj.page = res.data.current_page
    selectUserGroupPageObj.pageSize = res.data.page_size
    selectGroupUserList.value.push(...res.data.items)
    selectUserGroupLoading.value = false
  } catch (error) {
    selectUserGroupLoading.value = false
  }
}
init2()
const selectUserLoading = ref(false)
const selectUserPageObj = reactive({
  page: 1,
  total: 0,
  pageSize: 10,
})
const selectUserList = ref([])
const init3 = async (page = 1) => {
  if (selectUserLoading.value) return
  selectUserLoading.value = true
  try {
    const res = await userGroupApi.getUserInfoList({
      page,
      page_size: selectUserPageObj.pageSize,
    })
    selectUserPageObj.total = res.data.total
    selectUserPageObj.page = res.data.current_page
    selectUserPageObj.pageSize = res.data.page_size
    selectUserList.value.push(...res.data.items)
    selectUserLoading.value = false
  } catch (error) {
    selectUserLoading.value = false
  }
}
init3()
const crudContentRef = ref()
onMounted(async () => {
  await nextTick(() => {
    window.addEventListener('resize', settingFixedPage, false)
    settingFixedPage()
  })
})
const settingFixedPage = () => {
  const workAreaHeight = document.querySelector('.work-area').offsetHeight
  let tableHeight = workAreaHeight - 24 - 32 - 56 - 24
  if (crudContentRef.value) {
    crudContentRef.value.style.height = tableHeight + 'px'
  }
}
const dateFormat = computed(() => {
  return (val) => {
    if (!val) return '-'
    return tool.dateFormat(val)
  }
})
</script>
<style>
.arco-upload-list-picture img {
  object-fit: contain;
}
</style>
